<template>
  <el-table :stripe="stripe" :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
            v-bind="$props" :empty-text="emptyText" :data="processData" :span-method="objectSpanMethod">
    <slot/>
  </el-table>
</template>

<script>
export default {
  name: 'MergeTable',
  props: {
    tableData: {
      type: Array,
      default: () => []
    },
    mergeArr: { // 表格中需要合并的列名
      type: Array,
      default: () => []
    },
    emptyText: {
      type: String,
      default: '暂无数据' // 设置默认值
    },
    stripe: {
      type: Boolean,
      default: false // 设置默认值
    }
  },
  data() {
    return {
      mergeObj: {} // 用来记录需要合并行的下标
    }
  },
  computed: {
    processData() {
      // 在data发生变化时执行的操作
      this.getSpanArr(this.tableData)
      return this.tableData
    }
  },
  methods: {
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      if (this.mergeArr.indexOf(column.property) !== -1) {
        if (this.mergeObj[column.property][rowIndex]) {
          return [this.mergeObj[column.property][rowIndex], 1]
        } else {
          return [0, 0];
        }
      }
    },
    getSpanArr(data) {
      this.mergeArr.forEach((key, index1) => {
        let count = 0;
        this.mergeObj[key] = [];
        data.forEach((item, index) => {
          if (index === 0) {
            this.mergeObj[key].push(1);
          } else {
            let valid = true;
            for (let i = 0; i <= index1; i++) {
              const mergeKey = this.mergeArr[i];
              if (item[mergeKey] !== data[index - 1][mergeKey]) {
                valid = false;
                break;
              }
            }
            if (valid) {
              this.mergeObj[key][count] += 1;
              this.mergeObj[key].push(0);
            } else {
              count = index;
              this.mergeObj[key].push(1);
            }
          }
        });
      });
    }
  }
}
</script>
